package com.yyw.fileupload.controller;

import com.yyw.fileupload.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author V
 */
@RestController
@RequestMapping("/file")
public class FileUpload {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uploadImg(@RequestParam("assIma") MultipartFile file, HttpServletRequest request, String fileName,
                            @RequestParam(required = false, defaultValue = "0") int width, @RequestParam(required = false, defaultValue = "0") int height) {
        try {
            String filePath = request.getSession().getServletContext().getRealPath("files/");
            if (FileUtil.isImage(file.getInputStream())) { // 图片
                FileUtil.compressFile(file.getInputStream(), filePath, fileName, width, height);
                Thread.sleep(1000); // 1秒后返回地址
            } else {
                FileUtil.uploadFile(file.getBytes(), filePath, fileName);
            }
            logger.info("upload file success!");
            logger.info("file location: " + filePath + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return fileName;
    }

    /**
     * base64格式图片上传
     *
     * @param request
     * @param imgBase64Str
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/base64Upload", method = RequestMethod.POST)
    public Object uploadImgs(HttpServletRequest request, String imgBase64Str) {
        Map<String, Object> result = new HashMap<>();
        if (imgBase64Str != null && !"".equals(imgBase64Str.trim())) {
            String filePath = request.getSession().getServletContext().getRealPath("files/");
            String fileType = imgBase64Str.substring(imgBase64Str.indexOf("/") + 1, imgBase64Str.indexOf(";"));
            String fileName = System.currentTimeMillis() + ("" + Math.random()).replace(".", "") + "." + fileType;
            // 转换并上传
            boolean flag = FileUtil.imgBase64ToFile(imgBase64Str, filePath, fileName);
            if (flag) {
                result.put("sucFlag", true);
                result.put("message", fileName);
            } else {
                result.put("sucFlag", false);
                result.put("message", "base64转换图片文件失败!");
            }
        } else {
            result.put("sucFlag", false);
            result.put("message", "base64值不能为空!");
        }
        return result;
    }

}
